import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
    state: {
        skeletonLoading: true, //骨架屏开启
        hasLogin: false,
        userInfo: '',
        systemInfo: {},
        capsule: {},

        platform:'',
        statusBarHeight: '',
    },

    mutations: {
        setSkeletonLoading(state, provider) {
            setTimeout(() => {
                state.skeletonLoading = provider;
            }, 100);
        },
        setPlatform(state, provider) {
            state.platform = provider;
        },
        // 获取状态栏高度
        setBarHeight(state, provider) {
            state.statusBarHeight = provider;
        },
        //更新登录状态
        setHasLogin(state, provider) {
            state.hasLogin = provider;
        },

        //更新用户信息，写入信息
        updateUserInfo(state, provider) {
            console.log(state)
            state.userInfo = provider;
            uni.setStorageSync('userInfo', provider);
        },

        //更新分享用户信息
        updateShareUserInfo(state, provider) {
            state.shareUserInfo = provider;
        },

        setSystemInfo(state, provider) {
            state.systemInfo = provider;
        },
        setCapsule(state, provider) {
            state.capsule = provider;
        },
        //退出登录
        logout(state) {
            state.hasLogin = false;
            state.userInfo = {};
            uni.removeStorage({
                key: 'userInfo',
            });
            uni.reLaunch({
                url: '/pages/index/index',
            });
        },
    },

    actions: {
        Logout({ commit }) {
            return new Promise(resolve => {
                uni.clearStorage();
                commit('logout', {});
                resolve();
            });
        },

        // 获取用户信息并更新
        VAgetUser({ commit }, payload) {
            return new Promise((resolve, reject) => {
                getUserInfo({
                    access_token: uni.getStorageSync('token'),
                })
                    .then(res => {
                        commit('updateUserInfo', res.data);
                        commit('setHasLogin', true);
                        resolve(res);
                    })
                    .catch(err => {
                        uni.showToast({
                            title: err.msg,
                            icon: 'none',
                        });
                        reject(err);
                    });
            });
        },
    },
});

export default store;
